package com.elvish.efast.modules.sys.controller;

import com.elvish.efast.common.anno.NeedPage;
import com.elvish.efast.common.consts.Const;
import com.elvish.efast.common.entity.Page;
import com.elvish.efast.common.entity.Result;
import com.elvish.efast.common.entity.TableResponse;
import com.elvish.efast.common.enums.ResultCode;
import com.elvish.efast.common.utils.CommonUtil;
import com.elvish.efast.common.utils.ResultUtil;
import com.elvish.efast.modules.sys.entity.Role;
import com.elvish.efast.modules.sys.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.Lang;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * (TRole)表控制层
 *
 * @author makejava
 * @since 2018-11-15 14:21:51
 */
@RestController
@RequestMapping("/role")
@Slf4j
public class RoleController {
    /**
     * 服务对象
     */
    @Resource
    private RoleService tRoleService;

    /**
     * 查询角色列表
     *
     * @param page 分页信息
     * @param dict 查询参数
     * @return 响应消息
     */
    @GetMapping("/queryAll")
    @NeedPage
    public TableResponse queryAll(Page page, Role role) {
        return TableResponse.builder().data(tRoleService.queryAll(role)).build();
    }

    /**
     * 编辑角色
     *
     * @param oper 操作符
     * @param role 角色信息
     * @return 响应消息
     */
    @PostMapping("/editRole")
    public Result editDict(int oper, @RequestBody Role role) {
        Result result = null;
        try {
            if (oper == Const.OperationType.ADD) {
                role.setId(CommonUtil.uuid());
                this.tRoleService.insert(role);
            } else if (oper == Const.OperationType.UPDATE) {
                this.tRoleService.update(role);
            } else if (oper == Const.OperationType.DELETE) {
                String[] ids = role.getIds();
                if (Lang.isEmpty(ids)) {
                    ids = new String[1];
                    ids[0] = role.getId();
                }
                this.tRoleService.deleteByIds(ids);
            }
            result = ResultUtil.success();
        } catch (Exception e) {
            log.error("editRole error", e);
            result = ResultUtil.fail(ResultCode.ERROR);
        }
        return result;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Role selectOne(String id) {
        return this.tRoleService.queryById(id);
    }

}